package org.x.usermod.service.impl;


import ch.qos.logback.core.util.StringUtil;
import com.alibaba.fastjson2.JSON;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.x.commonmod.config.BusinessException;
import org.x.commonmod.config.Result;
import org.x.usermod.dto.SysRoleDTO;
import org.x.usermod.dto.SysRoleListDto;
import org.x.usermod.dto.SysRoleListSaveDTO;
import org.x.usermod.dto.SysRoleListUpdateDTO;
import org.x.usermod.entity.SysRole;
import org.x.usermod.entity.SysRoleAcl;
import org.x.usermod.mapper.SysRoleAclMapper;
import org.x.usermod.service.ISysRoleService;
import org.x.usermod.mapper.SysRoleMapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.x.usermod.vo.SysRoleVo;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 角色表 服务层实现。
 *
 * @author mybatis-flex-helper automatic generation
 * @since 1.0
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRoleAclMapper sysRoleAclMapper;

    /**
     * 获取角色列表
     */
    @Override
    public Page<SysRoleVo> pageList(SysRoleListDto sysRoleListDto) {
        //检验SysRoleListDto参数使否为空，不为空才构建查询条件
        QueryWrapper wrapper = new QueryWrapper();

        if(!StringUtil.isNullOrEmpty(sysRoleListDto.getName()))
        {
            wrapper.like(SysRole::getName, sysRoleListDto.getName());
        }
        if(!StringUtil.isNullOrEmpty(sysRoleListDto.getCode()))
        {
            wrapper.like(SysRole::getCode, sysRoleListDto.getCode());
        }
        if(!StringUtil.isNullOrEmpty(String.valueOf(sysRoleListDto.getDataScope())))
        {
            wrapper.like(SysRole::getDataScope, sysRoleListDto.getDataScope());
        }
        if(!StringUtil.isNullOrEmpty(String.valueOf(sysRoleListDto.getIsDelete())))
        {
            wrapper.like(SysRole::getIsDelete, sysRoleListDto.getIsDelete());
        }

        Page<SysRole> page = sysRoleMapper.paginate(
                sysRoleListDto.getPage(),
                sysRoleListDto.getSize(),
                wrapper
        );

        Page<SysRoleVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
       return pageVo;
    }

    /**
     * 编辑角色表即更新角色信息
     * @param sysRoleListUpdateDTO
     * @return
     */
    @Override
    public int update(SysRoleListUpdateDTO sysRoleListUpdateDTO) {
        //检验角色是否存在
        SysRole role = sysRoleMapper.selectOneById(sysRoleListUpdateDTO.getId());
        if (role != null)
        {
            BeanUtils.copyProperties(sysRoleListUpdateDTO, role);
            role.setUpdatedTime(new Date());
            sysRoleMapper.insertOrUpdateSelective( role);
            //更新数据权限范围
            sysRoleAclMapper.deleteByQuery(new QueryWrapper().eq("role_id", sysRoleListUpdateDTO.getId()));
            List<SysRoleAcl> acls = new ArrayList<>();
            for (long aclId : sysRoleListUpdateDTO.getAclIds())
            {
                SysRoleAcl acl = new SysRoleAcl();
                acl.setRoleId(sysRoleListUpdateDTO.getId());
                acl.setAclId(aclId);
                acl.setCreatedTime(new Date());
                acls.add(acl);
                sysRoleAclMapper.insertOrUpdateSelective(acl);
            }
        }
        return 0;

    }

    /**
     * 逻辑删除角色
     * @param id
     * @return
     */

    @Override
    public Result removeById(Integer id) {
        /**
         * 逻辑删除，设置is_delete=1
         * 检验角色是否存在
         */
        SysRole role = sysRoleMapper.selectOneById(id);
        if (role != null)
        {
            role.setIsDelete(1);
            sysRoleMapper.insertOrUpdateSelective(role);
            //清理角色权限关联
            sysRoleAclMapper.deleteByQuery(new QueryWrapper().eq("role_id", id));
        }
        return Result.ok("删除成功");
    }

    /**
     * 添加角色
     * @param sysRoleListSaveDTO
     * @return
     */

    @Override
    public String save(SysRoleListSaveDTO sysRoleListSaveDTO) {
        //检查角色是否已存在
        SysRole role = sysRoleMapper.selectOneByQuery(new QueryWrapper().eq("name", sysRoleListSaveDTO.getName()));
        if (role != null)
        {
            throw new BusinessException("角色已存在");
        }
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleListSaveDTO, sysRole);
        sysRole.setCreatedTime(new Date());
        sysRole.setIsDelete(0);
        sysRoleMapper.insert(sysRole);
        //关联sys_role_acl表
        List<SysRoleAcl> acls = new ArrayList<>();
        for (long Id : sysRoleListSaveDTO.getAclIds())
        {
            SysRoleAcl acl = new SysRoleAcl();
            acl.setRoleId(sysRole.getId());
            acl.setAclId(Id);
            acl.setCreatedTime(new Date());
            acls.add(acl);
        }
        return sysRoleAclMapper.insertBatch(acls) > 0 ? "添加成功" : "添加失败";
    }

    /**
     * 查询所有角色表
     * @param sysRoleDTO
     * @return
     */

    @Override
    public List<SysRole> allList(SysRoleDTO sysRoleDTO) {
        //获取所有角色列表
        List<SysRole> roles = sysRoleMapper.selectAll();
        return roles;
    }


}